package com.easy.modules.sysmgr.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.easy.common.dao.BaseDaoI;
import com.easy.common.dao.IBaseDao;
import com.easy.common.util.BeanUtils;
import com.easy.common.web.page.DataGrid;
import com.easy.common.web.page.Msg;
import com.easy.common.web.page.Pager;
import com.easy.modules.sysmgr.entity.MenuEntity;
import com.easy.modules.sysmgr.entity.PermitsEntity;
import com.easy.modules.sysmgr.entity.UserEntity;
import com.easy.modules.sysmgr.entity.UserRoleEntity;
import com.easy.modules.sysmgr.entity.UserWorkGroupEntity;
import com.easy.modules.sysmgr.service.PermitsServiceI;
import com.easy.modules.sysmgr.web.form.PermitsForm;

@Service
@Transactional
public class PermitsServiceImpl implements PermitsServiceI {

	@Autowired
	private IBaseDao<PermitsEntity> basedaoPermits;
	
	@Autowired
	private IBaseDao<MenuEntity> basedaoMenu;
	
	@Autowired
	private IBaseDao<UserWorkGroupEntity> basedaoWorkGroup;
	
	@Autowired
	private IBaseDao<UserRoleEntity> basedaoUserRole;
	
	@Autowired
	private BaseDaoI<UserEntity> basedaoUser;
	
	@Override
	public Msg save(PermitsForm form) {
		try {
			PermitsEntity entity = new PermitsEntity();
			BeanUtils.copyNotNullProperties(form, entity);
			entity.setCreated(new Date()) ;
			this.basedaoPermits.add(entity);
			return new Msg(true, "创建成功！") ;
		} catch (BeansException e) {
			return new Msg(false, "创建失败！") ;
		}
	}

	@Override
	public Msg delete(PermitsForm form) {
		try {
			if(null != form.getIds() && !"".equals(form.getIds())) {
				String[] ids = form.getIds().split(",") ;
				for (String id : ids) {
					this.basedaoPermits.delete(PermitsEntity.class, id) ;
				}
				return new Msg(true, "删除成功！") ;
			} else {
				return new Msg(false, "删除失败！") ;
			}
		} catch (BeansException e) {
			return new Msg(false, "删除失败！") ;
		}
	}
	
	@Override
	public Msg edit(PermitsForm form) {
		try {
			PermitsEntity entity = this.basedaoPermits.load(PermitsEntity.class, form.getId());
			
			if(entity != null) {
				form.setCreated(new Date()) ;
				BeanUtils.copyNotNullProperties(form, entity, new String[] { "created" });
				entity.setModifyDate(new Date()) ;
				
				this.basedaoPermits.update(entity) ;
			}
			
			return new Msg(true, "编辑成功！") ;
		} catch (BeansException e) {
			return new Msg(false, "编辑失败！") ;
		}
	}
	

	@Override
	public PermitsForm get(PermitsForm form) {
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = "select t from PermitsEntity t where 1=1";
		hql = addWhere(hql, form, params) ;
		
		PermitsEntity entity = (PermitsEntity) this.basedaoPermits.queryObject(hql, params) ;
		if(null != entity) {
			PermitsForm pform = new PermitsForm();
			BeanUtils.copyProperties(entity, pform);
			return pform;
		} else {
			return null ;
		}
	}

	@Override
	public DataGrid datagrid(PermitsForm form) {
		
		List<PermitsForm> forms = new ArrayList<PermitsForm>();
		Pager<PermitsEntity> pager = this.find(form) ;
		if (null != pager && !pager.getDataRows().isEmpty()) {
			for (PermitsEntity entity : pager.getDataRows()) {
				PermitsForm uf = new PermitsForm();
				BeanUtils.copyNotNullProperties(entity, uf);
				
				forms.add(uf);
			}
		}
		
		DataGrid datagrid = new DataGrid();
		datagrid.setTotal(pager.getTotal());
		datagrid.setRows(forms);
		return datagrid;
	}


	private Pager<PermitsEntity> find(PermitsForm form) {
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = "select t from PermitsEntity t where 1=1";
		hql = addWhere(hql, form, params) ;
		return this.basedaoPermits.find(hql, params);
	}


	private String addWhere(String hql, PermitsForm form, Map<String, Object> params) {
		if (null != form) {
			if (form.getId() != null && !"".equals(form.getId())) {
				hql += " and t.id=:id";
				params.put("id", form.getId());
			}
			if (form.getName() != null && !"".equals(form.getName())) {
				hql += " and t.name like :name";
				params.put("name", "%%" + form.getName() + "%%");
			}
		}
		return hql;
	}

	@Override
	public Msg addMenuRole(PermitsForm form) {
		try {
			PermitsEntity role = this.basedaoPermits.load(PermitsEntity.class, form.getId());
			
			if(null != form.getMenu_ids() && !"".equals(form.getMenu_ids())) {
				Set<MenuEntity> menus = new HashSet<MenuEntity>() ;
				String[] ids = form.getMenu_ids().split(",") ;
				for (String id : ids) {
					MenuEntity menu = this.basedaoMenu.load(MenuEntity.class, id) ;
					if(null != menu.getHref() && !"".equals(menu.getHref().trim())) {
						menus.add(menu) ;
					}
				}
				role.setMenus(menus) ;
			} else {
				role.setMenus(null) ;
			}
			
			this.basedaoPermits.update(role) ;
			
			return new Msg(true, "添加菜单到角色成功！") ;
		} catch (BeansException e) {
			return new Msg(false, "添加菜单到角色失败！") ;
		}
	}

	@Override
	public PermitsForm getRoleMenus(PermitsForm form) {
		Map<String, Object> params = new HashMap<String, Object>() ;
		params.put("id", form.getId()) ;
		PermitsEntity entity = (PermitsEntity) this.basedaoPermits.queryObject("select t from PermitsEntity t left join fetch t.menus menu where t.id=:id", params) ;
		if(null != entity) {
			PermitsForm f = new PermitsForm() ;
			BeanUtils.copyNotNullProperties(entity, f) ;
			
			Set<MenuEntity> menus = entity.getMenus() ;
			if (menus != null && !menus.isEmpty()) {
				boolean b = false;
				String ids = "";
				String names = "";
				for (MenuEntity m : menus) {
					if (b) {
						ids += ",";
						names += ",";
					} else {
						b = true;
					}
					ids += m.getId();
					names += m.getName() ;
				}
				f.setMenu_ids(ids) ;
				f.setMenu_names(names) ;
			}
			return f ;
		}
		return null;
	}

	@Override
	public Msg addWorkGroupPermits(PermitsForm form) {
		try {
			PermitsEntity permits = this.basedaoPermits.load(PermitsEntity.class, form.getId());
			if(null != form.getGroup_ids() && !"".equals(form.getGroup_ids())) {
				Set<UserWorkGroupEntity> groups = new HashSet<UserWorkGroupEntity>() ;
				String[] ids = form.getGroup_ids().split(",") ;
				for (String id : ids) {
					UserWorkGroupEntity group = this.basedaoWorkGroup.load(UserWorkGroupEntity.class, id) ;
					groups.add(group) ;
				}
				permits.setWorkgroups(groups) ;
			} else {
				permits.setWorkgroups(null) ;
			}
			
			this.basedaoPermits.update(permits) ;
			
			return new Msg(true, "分配权限组到工作组成功！") ;
		} catch (BeansException e) {
			return new Msg(false, "分配权限组到工作组失败！") ;
		}
	}
	
	@Override
	public Msg addUserRolePermits(PermitsForm form) {
		try {
			PermitsEntity permits = this.basedaoPermits.load(PermitsEntity.class, form.getId());
			if(null != form.getUserrole_ids() && !"".equals(form.getUserrole_ids())) {
				Set<UserRoleEntity> userroles = new HashSet<UserRoleEntity>() ;
				String[] ids = form.getUserrole_ids().split(",") ;
				for (String id : ids) {
					UserRoleEntity group = this.basedaoUserRole.load(UserRoleEntity.class, id) ;
					userroles.add(group) ;
				}
				permits.setUserroles(userroles) ;
			} else {
				permits.setUserroles(null) ;
			}
			
			this.basedaoPermits.update(permits) ;
			
			return new Msg(true, "分配权限组到用户角色成功！") ;
		} catch (BeansException e) {
			return new Msg(false, "分配权限组到用户角色失败！") ;
		}
	}

	@Override
	public PermitsForm getPermits(PermitsForm form) {
		Map<String, Object> params = new HashMap<String, Object>() ;
		params.put("id", form.getId()) ;
		PermitsEntity entity = (PermitsEntity) this.basedaoPermits.queryObject("select t from PermitsEntity t left join fetch t.workgroups g where t.id=:id", params) ;
		if(null != entity) {
			PermitsForm f = new PermitsForm() ;
			BeanUtils.copyNotNullProperties(entity, f) ;
			
			Set<UserWorkGroupEntity> groups = entity.getWorkgroups() ;
			if (groups != null && !groups.isEmpty()) {
				boolean b = false;
				String ids = "";
				String names = "";
				for (UserWorkGroupEntity m : groups) {
					if (b) {
						ids += ",";
						names += ",";
					} else {
						b = true;
					}
					ids += m.getId();
					names += m.getName() ;
				}
				f.setGroup_ids(ids) ;
				f.setGroup_names(names) ;
			}
			return f ;
		}
		return null;
	}

	@Override
	public Msg addUserPermits(PermitsForm form) {
		try {
			PermitsEntity permits = this.basedaoPermits.load(PermitsEntity.class, form.getId());
			if(null != form.getUser_ids() && !"".equals(form.getUser_ids())) {
				Set<UserEntity> users = new HashSet<UserEntity>() ;
				String[] ids = form.getUser_ids().split(",") ;
				for (String id : ids) {
					UserEntity user = this.basedaoUser.get(UserEntity.class, id) ;
					users.add(user) ;
				}
				permits.setUsers(users) ;
			} else {
				permits.setUsers(null) ;
			}
			
			this.basedaoPermits.update(permits) ;
			
			return new Msg(true, "分配权限组到用户成功！") ;
		} catch (BeansException e) {
			return new Msg(false, "分配权限组到用户失败！") ;
		}
	}

	@Override
	public PermitsForm getPermitsUsers(PermitsForm form) {
		Map<String, Object> params = new HashMap<String, Object>() ;
		params.put("id", form.getId()) ;
		PermitsEntity entity = (PermitsEntity) this.basedaoPermits.queryObject("select t from PermitsEntity t left join fetch t.users user where t.id=:id", params) ;
		if(null != entity) {
			PermitsForm f = new PermitsForm() ;
			BeanUtils.copyNotNullProperties(entity, f) ;
			
			Set<UserEntity> users = entity.getUsers() ;
			if (users != null && !users.isEmpty()) {
				boolean b = false;
				String ids = "";
				String names = "";
				for (UserEntity m : users) {
					if (b) {
						ids += ",";
						names += ",";
					} else {
						b = true;
					}
					ids += m.getId();
					names += m.getTruename() ;
				}
				f.setUser_ids(ids) ;
				f.setUser_names(names) ;
			}
			return f ;
		}
		return null;
	}
}
